package project.euler.honk.problem.to50;

final class Problem38 {

	private static boolean check(int value) {
		final boolean[] seen = new boolean[10];
		while (value > 0) {
			int c = value % 10;
			if (c == 0 || seen[c])
				return false;
			seen[c] = true;
			value /= 10;
		}
		return true;
	}

	private static int numDigits(int a) {
		if (a >= 100000000)
			return 9;
		if (a >= 10000000)
			return 8;
		if (a >= 1000000)
			return 7;
		if (a >= 100000)
			return 6;
		if (a >= 10000)
			return 5;
		if (a >= 1000)
			return 4;
		if (a >= 100)
			return 3;
		if (a >= 10)
			return 2;
		return 1;
	}

	private static int concat(int a, int b) {
		int x;
		switch (numDigits(b)) {
		case 1:
			x = 10;
			break;
		case 2:
			x = 100;
			break;
		case 3:
			x = 1000;
			break;
		case 4:
			x = 10000;
			break;
		case 5:
			x = 100000;
			break;
		case 6:
			x = 1000000;
			break;
		case 7:
			x = 10000000;
			break;
		default:
			x = 8;
		}
		return a * x + b;
	}

	public static void main(String[] args) {
		long start = System.currentTimeMillis();
		int max = 0;

		for (int current = 1;; current++) {
			if (numDigits(current) > 5)
				break;
			int bla = concat(current, 2 * current);
			for (int i = 3; i < 11; i++) {
				if (numDigits(current) * (i - 1) > 9)
					break;
				if (bla < 918273645) {
					bla = concat(bla, i * current);
					continue;
				}
				if (numDigits(bla) == 9) {
					if (bla > max && check(bla)) {
						max = bla;
					}
					break;
				}
				bla = concat(bla, i * current);
			}
		}
		long end = System.currentTimeMillis();
		System.out.println("Result: " + max + " Time: " + (end - start));
	}

}
